package com.wbj.direction.sensor.compass

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.util.AttributeSet
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.ImageView
import com.wbj.direction.sensor.BaseSensorView
import com.wbj.direction.R

/**
 * @auth : WANGCHUANGJUN
 * @mail : 910868438@qq.com
 * @desc : 指南针View
 * @date : 2021/12/13 11:11
 */

@SuppressLint("UseCompatLoadingForDrawables")
class CompassView : BaseSensorView {

    override val TAG = this::class.java.simpleName
    var currentDegree = 0f
    lateinit var ivCompass : ImageView

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initView()
    }

    private fun initView() {
        ivCompass = ImageView(context)
        var param = LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)
        ivCompass.layoutParams = param
        ivCompass.scaleType = ImageView.ScaleType.FIT_CENTER
        ivCompass.setImageResource(R.drawable.compass)
        addView(ivCompass)
    }

    override fun onSensorChanged(event: SensorEvent?) {
        var sensorType = event?.sensor?.type
        if (sensorType == Sensor.TYPE_ORIENTATION) {
            var degree = event?.values?.get(0)
            var rotateAnim = RotateAnimation(
                currentDegree,
                -degree!!,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
            rotateAnim.duration = 200
            ivCompass.startAnimation(rotateAnim)
            currentDegree = -degree
        }
    }

    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

    }
}